using BlazorAdmin.Models;
using BlazorAdmin.Models.Auth;
using BlazorAdmin.Interface;
using BootstrapBlazor.Components;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using BlazorAdmin.Services.DbService;

namespace BlazorAdmin.Services
{
    public class SettingsService : BaMgmtDbService, ISettings
    {
        public SettingsService(IPetaPoco db) : base(db) { }

        /// <summary>
        /// 保存、更新
        /// </summary>
        /// <param name="entity">实体对象</param>
        /// <returns>错误消息</returns>
        public Task<string> SaveSettings(Setting entity)
        {
            using var db = Create();
            bool isUpdate = entity.ID > 0;

            try
            {
                if (isUpdate)
                {
                    var prvEntity = db.FirstOrDefault<Setting>($"Where ID = {entity.ID}");

                    if (prvEntity.IsReadOnly == true)
                    {
                        return Task.FromResult($"{prvEntity.Code}配置不允许更新！");
                    }
                    else
                    {
                        //禁止更新以下字段
                        entity.Code = prvEntity.Code;
                    }

                    db.Update(entity);
                }
                else
                {
                    db.Insert(entity);
                }
            }
            catch (Exception ex)
            {

                return Task.FromResult($"保存出错，{ex.Message}");
            }

            return Task.FromResult(string.Empty);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询参数集合</param>
        /// <returns>分页数据</returns>
        public Task<QueryData<Setting>> GetSettingsList(AppQueryOption query)
        {
            var strSql = $"select * from {nameof(Setting)}s where 1=1";

            query.Sql = new(strSql, new { param = "value" });

            //注意：多表关联查询，需删除下面这行（默认false），否则过滤、查询会被当做内联查询，影响效率
            query.Sql.IsSingleTable = true;

            //注意：如果只查单表，且没有任何自定义参数，可以删除上面所有代码，直接return PageQueryAsync即可
            return PageQueryAsync<Setting>(query);
        }

        /// <summary>
        /// 获取实例
        /// </summary>
        /// <param name="id">主键id</param>
        /// <returns>实例对象</returns>
        public Task<Setting> GetSettings(int id)
        {
            using var db = Create();
            var entity = db.FirstOrDefault<Setting>("where ID = @0", id);

            return Task.FromResult(entity);
        }

        public Task<Setting> GetSettings(string code)
        {
            using var db = Create();
            var entity = db.FirstOrDefault<Setting>("where Code = @0", code);

            return Task.FromResult(entity);
        }

        /// <summary>
        /// 删除实例
        /// </summary>
        /// <param name="ids">主键id集合</param>
        /// <returns></returns>
        public Task<bool> DeleteSettings(List<int> ids)
        {
            using var db = Create();
            var count = db.Delete<Setting>($"where ID in ({string.Join(",", ids)})");

            return Task.FromResult(count > 0);
        }

        public Task<ApiAccount> GetApiAccount(string user)
        {
            using var db = Create();
            var entity = db.FirstOrDefault<Setting>("where Code = @0", user); // SysConsts.ApiAcct
            if (entity == null)
                return Task.FromResult(new ApiAccount());

            var acct = new ApiAccount() { User = user, Password = entity.Value, ExpireDays = 60 };
            return Task.FromResult(acct ?? new());
        }

        public async Task<string> GetSettingsVal(string code)
        {
            using var db = Create();
            var value = db.FirstOrDefault<string>($"select Value from {nameof(Setting)}s where Code = @0", code);

            return value ?? string.Empty;
        }
    }
}
